﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using NguyenHoa.Web.App_Code;
using NguyenHoa.Domains;
using NguyenHoa.Services;
using DevExpress.Web.ASPxGridView;
using System.Data.SqlClient;

namespace NguyenHoa.Web.Admin
{
  public partial class ProCategoryList : AdminBasePage
  {
    #region Properties
    private string m_innerError = string.Empty;
    private string ERR0001 = "fk_tblproduct_tblproductcategory";
    private string ERR0002 = "error|";

    internal override int RequiredPermission
    {
      get
      {
        return (int)FunctionList.Product;
      }
    }

    private int CategoryId
    {
      get
      {
        int Id = 0;
        int.TryParse(hfCategoryId.Value, out Id);
        return Id;
      }
    }

    private int LocaleId
    {
      get
      {
        int Id = 0;
        int.TryParse(hfLocaleId.Value, out Id);
        return Id;
      }
    }



    #endregion

    #region Events



    private void LoadPage()
    {
      xdsLanguage.DataFile = XmlStatusFile;
      cbxLanguage.Value = CurrentLanguage.Id;
    }

    protected void Page_Load(object sender, EventArgs e)
    {

      if (!IsCallback && !IsPostBack)
      {
        LoadPage();
        LoadList();
      }

      if (gvList.IsCallback)
      {
        LoadList();
      }
    }

    private string LoadLocale()
    {
      TList<ProCategoryLocale> listc = new ProCategoryLocaleService().GetByCategoryId(CategoryId);
      foreach (ProCategoryLocale item in listc)
      {
        if (item.LanguageId == (int)cbxLanguage.Value)
        {
          return string.Format("{0}|{1}|{2}|{3}", "[locale]", item.Id, item.Name, item.Description);
        }
      }
      return string.Format("{0}|{1}|{2}|{3}", "[locale]", 0, string.Empty, string.Empty);
    }

    protected void gvList_CustomCallback(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewCustomCallbackEventArgs e)
    {
      if (e.Parameters.StartsWith("locale"))
      {
        if (LocaleId == 0)
          SaveLocale();
        else
          UpdateLocale();
      }
    }

    protected void gvList_CustomJSProperties(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewClientJSPropertiesEventArgs e)
    {
      e.Properties["cpInnerError"] = m_innerError;
    }

    protected void gvList_RowDeleting(object sender, DevExpress.Web.Data.ASPxDataDeletingEventArgs e)
    {
      int Id = 0;
      int.TryParse(e.Keys["Id"].ToString(), out Id);
      Delete(Id);
      SetStateGrid(sender, e);
      //LoadList();
    }

    protected void gvList_RowInserting(object sender, DevExpress.Web.Data.ASPxDataInsertingEventArgs e)
    {
      string name = string.Empty;
      if (e.NewValues["Name"] != null)
      {
        name = e.NewValues["Name"].ToString();
      }
      Insert(name);
      SetStateGrid(sender, e);
      //LoadList();
    }

    protected void gvList_RowUpdating(object sender, DevExpress.Web.Data.ASPxDataUpdatingEventArgs e)
    {
      int Id = 0;
      int.TryParse(e.Keys["Id"].ToString(), out Id);
      string name = string.Empty;
      if (e.NewValues["Name"] != null)
      {
        name = e.NewValues["Name"].ToString();
      }
      Update(Id, name);
      SetStateGrid(sender, e);
      //LoadList();
    }

    protected void gvList_CellEditorInitialize(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewEditorEventArgs e)
    {
      if (e.Column.FieldName == "CreatedDate")
      {
        if (gvList.IsNewRowEditing || gvList.IsEditing)
        {
          e.Editor.Value = DateTime.Now;
          e.Editor.Enabled = false;
        }
        return;
      }

      if (e.Column.FieldName == "CreatedBy")
      {
        if (gvList.IsNewRowEditing || gvList.IsEditing)
        {
          // need recode
          e.Editor.Value = CurrentUser.Username;
          e.Editor.Enabled = false;
        }
      }
    }

    #endregion

    #region Methods

    private void LoadList()
    {
      gvList.DataSource = new ProductCategoryService().GetAll();
      gvList.DataBind();
    }

    private void SetStateGrid(object sender, System.ComponentModel.CancelEventArgs e)
    {
      ASPxGridView gv = sender as ASPxGridView;
      e.Cancel = true;
      gv.CancelEdit();
      LoadList();
    }

    private void Insert(string name)
    {
      if (string.IsNullOrEmpty(name))
      {
        m_innerError = ERR0002 + string.Format(Resources.Messages.ERR0007, Resources.Strings.Name);
        return;
      }
      ProductCategory pc = new ProductCategory();
      pc.Name = name;
      pc.Code = VietnameseString.Convert(name);
      pc.CreatedDate = DateTime.Now;
      pc.CreatedBy = CurrentUser.Username;
      try
      {
        ProductCategoryService pcservice = new ProductCategoryService();
        pcservice.Save(pc);
      }
      catch (Exception ex)
      {
        WriteLog("ProCategoryList::Insert ProductCategory", ex);
        m_innerError = ERR0002 + Resources.Messages.ERR0004;
      }
    }

    private void Update(int Id, string name)
    {
      if (Id == 0)
      {
        m_innerError = ERR0002 + Resources.Messages.ERR0004;
        return;
      }
      if (string.IsNullOrEmpty(name))
      {
        m_innerError = ERR0002 + string.Format(Resources.Messages.ERR0007, Resources.Strings.Name);
        return;
      }
      try
      {
        ProductCategoryService pcservice = new ProductCategoryService();
        ProductCategory pc = pcservice.GetById(Id);
        pc.Name = name;
        pc.Code = VietnameseString.Convert(name);
        pcservice.Update(pc);
      }
      catch (Exception ex)
      {
        WriteLog("ProductCategory.aspx::Update ProductCategory", ex);
        m_innerError = ERR0002 + Resources.Messages.ERR0004;
      }
    }

    private void Delete(int Id)
    {
      if (Id == 0)
      {
        m_innerError = ERR0002 + Resources.Messages.ERR0060;
        return;
      }
      try
      {
        if (new ProductService().GetByCategoryId(Id).Count > 0)
        {
          m_innerError = ERR0002 + string.Format(Resources.Messages.ERR0063, Resources.Strings.Category, Resources.Strings.Product);
          return;
        }
        ProductCategoryService pcservice = new ProductCategoryService();
        pcservice.DeleteAllById(Id);
      }
      catch (SqlException ex)
      {
        if (ex.Message.ToLower().IndexOf(ERR0001.ToLower()) != -1)
        {
          WriteLog("ProductCategory.aspx::Delete ProductCategory", ex);
          m_innerError = ERR0002 + string.Format(Resources.Messages.ERR0063, Resources.Strings.Category, Resources.Strings.Product);
        }
        else
          throw new Exception(ex.Message, ex);
      }
      catch (Exception ex)
      {
        WriteLog("ProductCategory.aspx::Delete ProductCategory", ex);
        m_innerError = ERR0002 + Resources.Messages.ERR0060;
      }
    }

    private string SaveLocale()
    {

      if (CategoryId == 0)
      {
        return m_innerError = ERR0002 + Resources.Messages.ERR0060;
      }
      if (string.IsNullOrEmpty(txtNameLocale.Text.Trim()))
      {
        return m_innerError = ERR0002 + string.Format(Resources.Messages.ERR0007, Resources.Strings.Name);
      }
      try
      {
        ProCategoryLocale cl = new ProCategoryLocale();
        cl.Name = txtNameLocale.Text.Trim();
        cl.Description = mmDescription.Text.Trim();
        cl.CategoryId = CategoryId;
        cl.LanguageId = (int)cbxLanguage.Value;
        new ProCategoryLocaleService().Save(cl);
        return "[save]";
      }
      catch (Exception ex)
      {
        WriteLog("ProductCategory.aspx::Save ProCategoryLocale", ex);
        return ERR0002 + Resources.Messages.ERR0060;
      }

    }

    private string UpdateLocale()
    {
      if (LocaleId == 0)
      {
        return ERR0002 + Resources.Messages.ERR0060;
      }
      if (string.IsNullOrEmpty(txtNameLocale.Text.Trim()))
      {
        return ERR0002 + string.Format(Resources.Messages.ERR0007, Resources.Strings.Name);
      }
      try
      {
        ProCategoryLocaleService cs = new ProCategoryLocaleService();
        ProCategoryLocale c = cs.GetById(LocaleId);
        c.Name = txtNameLocale.Text.Trim();
        c.Description = mmDescription.Text.Trim();
        cs.Update(c);
        return "[save]";
      }
      catch (Exception ex)
      {
        WriteLog("ProductCategory.aspx::Update ProCategoryLocale", ex);
       return ERR0002 + Resources.Messages.ERR0060;
      }
    }

    #endregion

    protected void gvList_CommandButtonInitialize(object sender, ASPxGridViewCommandButtonEventArgs e)
    {
      if (!CanDelete && e.Button.ButtonType == ColumnCommandButtonType.Delete)
        e.Visible = false;
      if (!CanModify && e.Button.ButtonType == ColumnCommandButtonType.Edit)
      {
        e.Visible = false;
      }
      if (!CanModify && e.Button.ButtonType == ColumnCommandButtonType.New)
      {
        e.Visible = false;
      }
    }

    protected void gvList_DataBound(object sender, EventArgs e)
    {
      if (!CanModify)
      {
        (gvList.Columns["Command"] as DevExpress.Web.ASPxGridView.GridViewCommandColumn).NewButton.Visible = false;
        (gvList.Columns["Locale"] as DevExpress.Web.ASPxGridView.GridViewColumn).Visible = false;
      }
    }

    protected void CtrlCallback_Callback(object source, DevExpress.Web.ASPxCallback.CallbackEventArgs e)
    {
      if (e.Parameter.StartsWith("loadlocale"))
      {
        e.Result = LoadLocale();
      }
      else if (e.Parameter.StartsWith("save"))
      {
        if(LocaleId==0)
          e.Result = SaveLocale();
        else
          e.Result = UpdateLocale();
      }
    }


  }
}
